<?php

namespace App\Console\Commands;

use App\Common\ApiReturn;
use App\Models\Commodity;
use App\Models\CommodityImage;
use App\Models\CommodityOrder;
use App\Models\CommoditySku;
use App\Models\Good;
use App\Models\GroupBuy;
use App\Models\Order;
use App\Models\Shop;
use App\Models\Yhzs\Lottery;
use App\Models\Yhzs\LotteryRoom;
use EasyWeChat\Factory;
use Elasticsearch\ClientBuilder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Img;

class CheckOrderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $order = CommodityOrder::where('order_status', 1)->get();
        $ids = [];
        foreach ($order as $key => $value) {
            $long = time() - strtotime($value->created_at);
            if ($long / 60 > 5) {
                $ids[] = $value->id; // 支付超时
            }

            if ($value->is_group_buy) {
//                $query->whereRaw(\DB::raw("find_in_set('$filtrationType',property_class)"));
                $groupOrder = GroupBuy::whereRaw(DB::raw("find_in_set({$value->id},order_ids)"))->first();
                if (!$groupOrder->order_ids || !$groupOrder->user_ids) {
                    continue;
                }
                $orderArr = explode(',', $groupOrder->order_ids);
                $userArr = explode(',',$groupOrder->user_ids);
                $orderKey = array_search($value->id, $orderArr);
                $userKey = array_search($value->customer_id, $userArr);
                unset($orderArr[$orderKey]);
                unset($userArr[$userKey]);
                $groupOrder->order_ids = implode(',', $orderArr);
                $groupOrder->user_ids = implode(',', $userArr);
                $groupOrder->join_number -= 1;
                $groupOrder->save();
            }
        }
        CommodityOrder::whereIn('id', $ids)->update(['order_status' => 5]);

    }


}
